﻿using System;
using System.Linq;
using System.Xml.Linq;
using OrderingPlatform.Model;
using OrderingPlatform.Model.UserManage;
using OrderingPlatform.MvcExtension;
using OrderingPlatform.Infrastructure;

namespace OrderingPlatform.DalService.UserManage
{
    public class UserDal
    {

        /// <summary>
        /// <para> 功    能： 获取当前登录用户名称 </para>
        /// <para> 作    者： 韩保新 </para>
        /// <para> 创建日期： 2011-11-8</para>
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentUserCode()
        {
            return System.Web.HttpContext.Current.User.Identity.Name;
        }

        /// <summary>
        /// <para> 功    能： 获取当前如何ID </para>
        /// <para> 作    者： 韩保新 </para>
        /// <para> 创建日期： 2011-11-8</para>
        /// </summary>
        /// <returns></returns>
        public static Guid GetCurrentUserId()
        {
            var r = GetUserModel();
            return r.UserId;
        }

        /// <summary>
        /// <para> 功    能： 获取当前用户集合信息 </para>
        /// <para> 作    者： 韩保新 </para>
        /// <para> 创建日期： 2011-11-8</para>
        /// </summary>
        /// <returns></returns>
        public static UserCurrentModel GetUserModel(string userCode = null)
        {
            if (string.IsNullOrEmpty(userCode))
                userCode = GetCurrentUserCode();
            if(string.IsNullOrEmpty(userCode))
                return new UserCurrentModel();
            var key = string.Format(ConstLibrary.OrderingUser + "-{0}", userCode);
            var str = DataCache.GetCache(key, ConstLibrary.SystemCashe);
            if (string.IsNullOrEmpty(str))
            {

                UserCurrentModel model;
                using (var db = new OrderingPlatformDbEntities())
                {
                    var reg = (from u in db.UserBases
                               where u.State == true && u.UserCode == userCode
                               select new UserCurrentModel
                               {
                                   UserId = u.UserId,
                                   UserCode = u.UserCode,
                                   Category = u.Category
                               }).FirstOrDefault();
                   
                    model = reg;

                }
                DataCache.SetCache(key, model.ToJson(), 60, ConstLibrary.SystemCashe);
                return model;

            }
            return str.JsonToObject<UserCurrentModel>();
        }

        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool CheckLogin(LogOnModel model)
        {
            using (var db = new OrderingPlatformDbEntities())
            {
                return
                      db.UserBases.Any(
                          a => a.UserCode == model.UserCode && a.LogPasswordMd5 == model.Password && a.State == true);
            }
        }

        /// <summary>
        /// 新增登录日志
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
       

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public CallBackModel AddUserBase(UserBase model)
        {
            var result = new CallBackModel
                {
                    State = 0
                };
            if (string.IsNullOrEmpty(model.Category) ||
                !new[] { ConstLibrary.CategoryCompanyName, ConstLibrary.CategoryUserName }.Contains(model.Category))
            {
                result.Message = "非法操作，如有疑问请联系管理员！";
                return result;
            }
            model.UserId = Guid.NewGuid();
            model.CreateDate = model.CreateDate ?? DateTime.Now;
            model.Points = 0;
            model.State = true;
            using (var db = new OrderingPlatformDbEntities())
            {
                var r = db.UserBases.Any(a => a.UserCode == model.UserCode && a.State == true);
                if (!r)
                {

                    db.UserBases.Add(model);
                    db.SaveChanges();
                    result.State = 1;
                }
                else
                {
                    result.Message = "已存在此用户名！";
                }
                return result;
            }
        }

        /// <summary>
        /// 清除用户Cashe
        /// </summary>
        /// <param name="userCode"></param>
        public static void ClearUserCashe(string userCode = null)
        {
            if (string.IsNullOrEmpty(userCode))
                userCode = GetCurrentUserCode();
            var key = string.Format(ConstLibrary.OrderingUser + "-{0}", userCode);

            DataCache.RemoveItemFromCache(key, ConstLibrary.SystemCashe);

        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public CallBackModel ModifyPassword(MobifyPasswordModel model)
        {
            var userId = GetCurrentUserId();
            var result = new CallBackModel
                {
                    State = 0
                };
            using (var db = new OrderingPlatformDbEntities())
            {
              var enty=  db.UserBases.FirstOrDefault(a => a.UserId == userId && a.LogPasswordMd5 == model.OrigonPassword&&a.State==true);
                if (enty != null)
                {
                    enty.LogPassword = model.ConfirmPassword;
                    enty.LogPasswordMd5 = model.Password;
                    db.SaveChanges();
                    result.State = 1;
                }
                else
                {
                    result.Message = "原始密码错误！";
                }
                return result;
            }
        }
    }
}
